﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.DataObjects.Networks;
using DiscoveryLogic.Common.Utilities;

namespace DiscoveryLogic.Analytics.BusinessLogic.Exports
{
    public class PajekExportUtil
    {
        public static void ExportNetworkToPajek(Network network, string tgtFilePath)
        {
            if(File.Exists(tgtFilePath))
                File.Delete(tgtFilePath);

            StreamWriter writer = new StreamWriter(tgtFilePath);

            writer.WriteLine("/* {0} */", Padding("Exported from Analytics Studio", 50));
            writer.WriteLine("/* {0} */", Padding("Network name: " + network.NetworkName, 50));
            writer.WriteLine("/* {0} */", Padding("Author: "+ network.Author, 50));
            writer.WriteLine("/* {0} */", Padding("Created on: " + network.CreatedOn.ToShortDateString(), 50));

            writer.WriteLine("*Vertices {0}", network.Records.Count);
            Dictionary<EntityBase, int> vMappings=new Dictionary<EntityBase, int>();
            int vIdx = 0;
            foreach(EntityBase entity in network.Records)
            {
                vIdx++;
                writer.WriteLine("{0} \"{1}[{2}]\"", vIdx, entity.Name, entity.EntityType.ToString());
                vMappings.Add(entity, vIdx);
            }
            writer.WriteLine("*Edges {0}", network.Links.Count);
            foreach(Link link in network.Links)
            {
                EntityBase fromE = null;
                EntityBase toE = null;
                foreach(EntityBase e in vMappings.Keys)
                {
                    if(link.FromType==EntityTypeUtil.GetType(e.EntityType) && link.FromKey==e.PKValue())
                        fromE = e;
                    if (link.ToType == EntityTypeUtil.GetType(e.EntityType) && link.ToKey == e.PKValue())
                        toE = e;
                }
                if(fromE !=null && toE !=null)
                {
                    writer.WriteLine("{0} {1}", vMappings[fromE], vMappings[toE]);
                }
            }

            writer.Flush();
            writer.Close();
        }

        private static string Padding(string input, int length)
        {
            if(input.Length<length)
            {
                while(input.Length < length)
                {
                    input = input + " ";
                }
            }
            return input;
        }

        
    }
}
